"""
    微博接口公共库
"""

from loguru import logger
import requests


def get_cookie():
    # 读取cookie.txt文件
    with open('./cookie.txt', 'r') as f:
        cookie = f.read()
        return cookie


def get_cookie_value(cookie_str: str, key: str) -> str:
    """
    从 Cookie 字符串中获取指定 key 的值
    :param cookie_str: 完整的 Cookie 字符串
    :param key: 要获取的 Cookie 名称
    :return: 对应的值，如果不存在返回空字符串
    """
    cookies = cookie_str.split(';')
    for cookie in cookies:
        cookie = cookie.strip()
        if cookie.startswith(key + "="):
            return cookie[len(key) + 1:]  # 去掉 key= 前缀
    return ""  # 没找到返回空字符串


def get_web_post_list(tye=1):
    """
    获取微博发布列表
    :param tye: 1 所有 2 关注者
    :return: 帖子列表
    """
    cookie = get_cookie()
    url = f'https://weibo.com/ajax/feed/unreadfriendstimeline?list_id=100018421914083&refresh=4&since_id=0&count=15'
    headers = {
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/89.0.4389.90 Safari/537.36',
        'cookie': cookie,
        'referer': 'https://weibo.com/',
        'x-xsrf-token': '',
    }
    response = requests.get(url, headers=headers)
    data = response.json()
    arr = []
    for i in data['statuses']:
        arr.append({
            'id': i['id'],
            'content': i['text_raw'],
            'uid': i['user']['id'],
            'comments_count': i['comments_count'],
            # 是否关注它
            'following': i['user']['following'],
        })
    return arr


def push_weibo_comment(post_id, content, uid):
    """
      微博帖子评论
      :param post_id: 帖子id
      :param content: 评论内容
      :param uid: 用户id
      :return: 评论结果
      """
    cookie = get_cookie()
    url = f'https://weibo.com/ajax/comments/create'
    headers = {
        "cookie": cookie,  # 登录态
        "x-xsrf-token": get_cookie_value(cookie,'XSRF-TOKEN'),
        "referer": "https://weibo.com/",

    }
    data = {
        'id': post_id,
        'comment': content,
    }
    response = requests.post(url, headers=headers, json=data)
    if response.status_code != 200:
        return False
    else:
        return {
            "post_id": post_id,
            "comment": content,
            "uid": uid,
        }


def get_weibo_comment_reply_list():
    """
    获取微博评论回复列表
    :return: 评论回复列表
    """
    cookie = get_cookie()
    url ='https://weibo.com/ajax/message/cmt'
    headers = {
        "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/89.0.4389.90 Safari/537.36",
        "cookie": cookie,
        "x-xsrf-token":'',
        'referer':'https://weibo.com/comment/inbox'
    }
    response = requests.get(url, headers=headers)
    if response.status_code != 200:
        return False
    res =  response.json()
    data = []
    for i in res['data']['comments']:
        if i.get('reply_original_text', '') != '':
            data.append({
                # 帖子id
                'post_id': i['status']['id'],
                # 向我回复的评论id
                'cid':i['id'],
                # 评论内容
                'content': i.get('reply_original_text', ''),
                # 用户id
                'uid':i['user']['id'],
                # 是否关注它
                'following': i['user']['following'],
            })
    return data

def push_weibo_comment_reply(post_id,cid,comment):
    """
      微博帖子评论回复
      :param post_id: 帖子id
      :param cid: 向我评论的id
      :param comment: 回复内容
      :return: 评论结果
      """
    cookie = get_cookie()
    url = f'https://weibo.com/ajax/comments/reply'
    headers = {
        "authority": "weibo.com",
        "accept": "application/json, text/plain, */*",
        "accept-language": "zh-CN,zh;q=0.9",
        "content-type": "application/json",
        "origin": "https://weibo.com",
        "referer": "https://weibo.com/comment/inbox",  # 你的帖子页面
        "user-agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/115.0 Safari/537.36",
        "x-requested-with": "XMLHttpRequest",  # 明是 Ajax 请求
        "x-xsrf-token": "RPbwdnD04OGqBVJlgTaMYqtG",  # 来自 Cookie/meta
        "cookie": cookie,  # 登录态
    }
    data = {
        'id': post_id,
        'cid': cid,
        'comment': comment,
    }
    response = requests.post(url, headers=headers, json=data)
    if response.status_code != 200:
        return False
    else:
        return  data


def push_weibo_post(msg):
    """
      微博发布
      :param msg: 发布内容
      :return: 发布结果
      """
    cookie = get_cookie()
    url = "https://weibo.com/ajax/statuses/update"
    headers={
        "content-type":"application/x-www-form-urlencoded",
        "cookie": cookie,
        "referer":"https://weibo.com/",
        "x-xsrf-token" :get_cookie_value(cookie,'XSRF-TOKEN')
    }

    response = requests.post(url, headers=headers, data={
        "content": msg
    })
    res = response.json()
    if res['ok'] == 1:
        return True
    else:
        err= res.get('msg', '未知错误')
        logger.error(f"微博发帖失败:{err}")
        return False

